package com.laicunba.service.fuiou.impl;

import java.io.ByteArrayInputStream;
import java.util.HashMap;
import java.util.Map;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import com.laicunba.constant.GloabConstant;
import com.laicunba.service.fuiou.FuiouOrderQueryService;
import com.laicunba.service.fuiou.FuiouOrderCreateService.CreateOrderResult;
import com.laicunba.util.HttpUtil;
import com.laicunba.util.StringUtil;

@Service
public class FuiouOrderQueryServiceImpl implements FuiouOrderQueryService {
	private static final Logger LOG = Logger.getLogger(FuiouOrderQueryServiceImpl.class);

	@SuppressWarnings({ "unchecked", "rawtypes" })
	@Override
	public QueryResult query(String orderId) {
		String sign = StringUtil.md5(String.format("%s|%s|%s", GloabConstant.FUIOU_MCHNTCD, orderId, GloabConstant.FUIOU_MCHNT_KEY));
		String fm = "<FM><MchntCd>%s</MchntCd><OrderId>%s</OrderId><Sign>%s</Sign></FM>";
		fm = String.format(fm, GloabConstant.FUIOU_MCHNTCD, orderId, sign);
		Map parameter = new HashMap();
		parameter.put("FM", fm);
		try {
			String xmlResult = HttpUtil.doPost(GloabConstant.FUIOU_URL_PREFIX + "/findPay/queryOrderId.pay", parameter);
			DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
			DocumentBuilder builder;
			System.out.println(xmlResult);
			QueryResult result = new QueryResult();
			builder = factory.newDocumentBuilder();
			Document doc = builder.parse(new ByteArrayInputStream(xmlResult.getBytes()));

			result.setRcd(getValue(doc, "Rcd"));
			result.setRdesc(getValue(doc, "RDesc"));
			result.setSign(getValue(doc, "Sign"));
			return result;
		} catch (Exception e) {
			LOG.error("到富友查找订单[" + orderId + "]状态出错:", e);
		}
		return null;
	}

	private String getValue(Document doc, String tagName) {
		NodeList nodeList = doc.getElementsByTagName(tagName);
		if (nodeList == null || nodeList.getLength() == 0) {
			return null;
		}
		Element e = (Element) nodeList.item(0);
		return e.getTextContent();
	}
}
